package com.aaa.backsystem.controller;

import com.aaa.backsystem.entity.*;
import com.aaa.backsystem.service.DicService;
import com.aaa.backsystem.service.SaleService;
import com.aaa.backsystem.util.MyConstants;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gyc
 * @since 2020-07-23
 */
@Controller
@RequestMapping("/sale")
public class SaleController extends BaseController{

    @Autowired
    private SaleService saleService;

    @Autowired
    private DicService dicService;

    @RequestMapping("/toStatMap")
    public String toStatMap(Model model) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<Sale> buyYear = saleService.findBuyYear(user.getUserId());
        model.addAttribute("buyYear", buyYear);
        return "stat/statMap";
    }

    @RequestMapping("/toShowSale")
    public String toShowPetrolStation() {
        return "sale/saleList";
    }



    /**
     * 查询列表
     **/
    @GetMapping("/saleList")
    @ResponseBody
    public LayuiTable saleList(Integer page, Integer limit, String beginDate, String endDate,String purchasePurpose){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        LayuiTable layuiTable = new LayuiTable();
        Wrapper wrapper = new EntityWrapper();
        //添加模糊查询的条件
        if (null != purchasePurpose && !"".equals(purchasePurpose)) {
            wrapper.like("purpose", purchasePurpose);
        }
        if ((null != beginDate && !"".equals(beginDate))&&(null != endDate && !"".equals(endDate))) {
            wrapper.between("buy_time", beginDate,endDate);
        }
        wrapper.eq("del_flag", 0);
        if(user.getPetrolStationId()!=null&&!"".equals(user.getPetrolStationId())){
            wrapper.eq("petrol_station_id",user.getPetrolStationId());
        }

        int saleListCount = saleService.selectCount(wrapper);
        //如果表中没有数据,则不进行分页查询
        if(saleListCount>0){
            //获取当前的系统毫秒数
            long start = System.currentTimeMillis();
            Page<Sale> pageInfo = new Page(page,limit);
            Page<Sale> deptPage = saleService.selectPage(pageInfo, wrapper);
            List<Sale> deptList = deptPage.getRecords();
            //从分页结果中提取list集合

            layuiTable.setCode(MyConstants.OPERATION_SUCCESS_CODE);
            layuiTable.setMsg(MyConstants.OPERATION_SUCCESS_MESSAGE);
            layuiTable.setData(deptList);
            layuiTable.setCount(saleListCount);
            long end = System.currentTimeMillis();
            System.out.println("============查询花费时间: "+(end-start)+"================");
            return layuiTable;
        }else {
            return layuiTable;
        }
    }

    /**
     * 多行删除（逻辑删除）
     *
     * @param saleList
     * @return
     */
    @RequestMapping("/deleteSales")
    @ResponseBody
    public Result deleteBatchUser(@RequestBody List<Sale> saleList) {
        List<Sale> saleListNew = new ArrayList<>();
        for (Sale sale : saleList) {
            Sale saleNew = new Sale();
            saleNew.setDelFlag("1");
            saleNew.setSaleId(sale.getSaleId());
            saleListNew.add(saleNew);
        }
        boolean flag = saleService.updateBatchById(saleListNew);
        if (flag) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 保存
     * @param sale
     * @return
     */
    @RequestMapping("/saveSale")
    @ResponseBody
    public Result saveSale(@RequestBody Sale sale){
        Result result = new Result();
        //获取登陆用户信息
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //获取登陆人的加油站ID进行判断
        if(user.getPetrolStationId()!=null){
            //将加油站id加入sale实体类
            sale.setPetrolStationId(user.getPetrolStationId());
            //日期转格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if(sale.getBirth()!=null && !"".equals(sale.getBirth())){
                Date birth = sale.getBirth();
                String format = sdf.format(birth);
                sale.setBirth(java.sql.Date.valueOf(format));
            }
            if(sale.getBuyTime()!=null && !"".equals(sale.getBuyTime())){
                Date buyTime = sale.getBuyTime();
                String s = sdf.format(buyTime);
                sale.setBuyTime(java.sql.Date.valueOf(s));
            }
            sale.setDelFlag("0");
            boolean insert = saleService.insert(sale);
            if(insert){
                return super.success();
            }else{
                return super.error();
            }
        }else{
            result.setMsg("您不是法人不能进行添加操作");
            result.setCode(MyConstants.OPERATION_FAIL_CODE);
            return result;
        }
    }

    /**
     * 修改
     * @param sale
     * @return
     */
    @RequestMapping("/updateSale")
    @ResponseBody
    public Result updateSale(@RequestBody Sale sale){
        Result result = new Result();
        //获取登陆用户信息
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //获取登陆人的加油站ID进行判断
        if(user.getPetrolStationId()!=null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if(sale.getBirth()!=null && !"".equals(sale.getBirth())){
                Date birth = sale.getBirth();
                String format = sdf.format(birth);
                sale.setBirth(java.sql.Date.valueOf(format));
            }
            if(sale.getBuyTime()!=null && !"".equals(sale.getBuyTime())){
                Date buyTime = sale.getBuyTime();
                String s = sdf.format(buyTime);
                sale.setBuyTime(java.sql.Date.valueOf(s));
            }
            boolean update = saleService.updateById(sale);
            if(update){
                return super.success();
            }else{
                return super.error();
            }
        }else{
            result.setMsg("您不是法人不能进行编辑操作");
            result.setCode(MyConstants.OPERATION_FAIL_CODE);
            return result;
        }
    }


    /**
     * 根据不同加油站获取散装油售卖信息
     * @return
     */
    @RequestMapping("/bathSale")
    @ResponseBody
    public Result bathSale(String year){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        try {
            List<EchartsDataBo> bathSale = saleService.findBathSale(year, user.getUserId());

            if (bathSale != null && bathSale.size() > 0) {
                return success(bathSale);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return error();
    }
}

